package com.opennews.openplatform

import groovy.transform.CompileDynamic
import groovy.transform.CompileStatic
import org.springframework.beans.factory.annotation.Value

@CompileStatic
class AMapHelper {
    @Value('${openplatform.amap.restApiUrl}')
    String restApiUrl

    @Value('${openplatform.amap.webApiKey}')
    String webApiKey

    final String version = "v3"
    final String successStatus = "1"

    /**
     * Queries location by coordinate.
     * @param latitude
     * @param longitude
     */
    @CompileDynamic
    Map<String, ?> queryByCoordinate(double latitude, double longitude) {
        try {
            final response = HttpRequestHelper.get(restApiUrl, "$version/geocode/regeo", [:], [
                key: webApiKey,
                location: "$longitude,$latitude",
            ])

            return response.status == successStatus ?
                 [
                    latitude: latitude,
                    longitude: longitude,
                    country: getStringValue(response.regeocode.addressComponent.country),
                    province: getStringValue(response.regeocode.addressComponent.province),
                    city: getStringValue(response.regeocode.addressComponent.city),
                    district: getStringValue(response.regeocode.addressComponent.district),
                    township: getStringValue(response.regeocode.addressComponent.township),
                    formattedAddress: getStringValue(response.regeocode.formatted_address),
                    adCode: getStringValue(response.regeocode.addressComponent.adcode),
                    cityCode: getStringValue(response.regeocode.addressComponent.citycode),
                    townCode: getStringValue(response.regeocode.addressComponent.towncode)
                ] : null
        } catch(Exception) {
            return null
        }
    }

    /**
     * Queries poi by keywords.
     * @param keywords
     */
    List<Map<String, ?>> queryPoiByKeywords(String keywords) {
        try {
            final response = HttpRequestHelper.get(restApiUrl, "$version/place/text", [:], [
                key: webApiKey,
                keywords: keywords,
            ])

            return response.status == successStatus ? response.pois as List<Map<String, ?>> : []
        } catch(Exception) {
            return []
        }
    }

    /**
     * If coordinate is outside of China item of response will be an empty list instead of string.
     * That's why we need to check on it.
     * @param item
     * @return
     */
    private String getStringValue(item) {
        return item instanceof List ? "" : item
    }
}
